// 出勤状态类型
export type AttendanceStatus = 'present' | 'absent' | 'leave' | 'late';

// 出勤记录类型定义
export interface AttendanceRecord {
  id: string;
  studentId: string;
  studentName: string;
  courseId: string;
  courseName: string;
  teacherId: string;
  teacherName: string;
  scheduleId: string;
  date: string;
  startTime: string;
  endTime: string;
  status: AttendanceStatus;
  reason?: string; // 请假或迟到原因
  remark?: string; // 备注
  recordedBy: string; // 记录人
  recordTime: string; // 记录时间
}

// 请假申请类型定义
export interface LeaveRequest {
  id: string;
  studentId: string;
  studentName: string;
  courseId: string;
  courseName: string;
  startDate: string;
  endDate: string;
  reason: string;
  status: 'pending' | 'approved' | 'rejected';
  submittedTime: string;
  approvedBy?: string;
  approvedTime?: string;
}

// 统计数据类型定义
export interface AttendanceStatistics {
  courseId: string;
  courseName: string;
  totalStudents: number;
  presentCount: number;
  absentCount: number;
  leaveCount: number;
  lateCount: number;
  attendanceRate: number;
}

// 模拟出勤记录数据
export const mockAttendanceRecords: AttendanceRecord[] = [
  {
    id: 'A001',
    studentId: '2023001',
    studentName: '张三',
    courseId: 'C001',
    courseName: '高等数学',
    teacherId: 'T001',
    teacherName: '李教授',
    scheduleId: 'S001',
    date: '2024-03-01',
    startTime: '08:00',
    endTime: '10:00',
    status: 'present',
    recordedBy: '李教授',
    recordTime: '2024-03-01 10:10'
  },
  {
    id: 'A002',
    studentId: '2023002',
    studentName: '李四',
    courseId: 'C001',
    courseName: '高等数学',
    teacherId: 'T001',
    teacherName: '李教授',
    scheduleId: 'S001',
    date: '2024-03-01',
    startTime: '08:00',
    endTime: '10:00',
    status: 'late',
    reason: '迟到10分钟',
    recordedBy: '李教授',
    recordTime: '2024-03-01 10:10'
  },
  {
    id: 'A003',
    studentId: '2023003',
    studentName: '王五',
    courseId: 'C001',
    courseName: '高等数学',
    teacherId: 'T001',
    teacherName: '李教授',
    scheduleId: 'S001',
    date: '2024-03-01',
    startTime: '08:00',
    endTime: '10:00',
    status: 'leave',
    reason: '生病请假',
    recordedBy: '李教授',
    recordTime: '2024-03-01 10:10'
  },
  {
    id: 'A004',
    studentId: '2023004',
    studentName: '赵六',
    courseId: 'C001',
    courseName: '高等数学',
    teacherId: 'T001',
    teacherName: '李教授',
    scheduleId: 'S001',
    date: '2024-03-01',
    startTime: '08:00',
    endTime: '10:00',
    status: 'absent',
    remark: '无故缺席',
    recordedBy: '李教授',
    recordTime: '2024-03-01 10:10'
  },
  {
    id: 'A005',
    studentId: '2023001',
    studentName: '张三',
    courseId: 'C002',
    courseName: '程序设计基础',
    teacherId: 'T002',
    teacherName: '王老师',
    scheduleId: 'S002',
    date: '2024-03-02',
    startTime: '10:30',
    endTime: '12:30',
    status: 'present',
    recordedBy: '王老师',
    recordTime: '2024-03-02 12:40'
  }
];

// 模拟请假申请数据
export const mockLeaveRequests: LeaveRequest[] = [
  {
    id: 'L001',
    studentId: '2023003',
    studentName: '王五',
    courseId: 'C001',
    courseName: '高等数学',
    startDate: '2024-03-01',
    endDate: '2024-03-01',
    reason: '生病需要就医',
    status: 'approved',
    submittedTime: '2024-02-29 18:30',
    approvedBy: '李教授',
    approvedTime: '2024-03-01 07:00'
  },
  {
    id: 'L002',
    studentId: '2023005',
    studentName: '孙七',
    courseId: 'C002',
    courseName: '程序设计基础',
    startDate: '2024-03-05',
    endDate: '2024-03-06',
    reason: '家中有事需要请假',
    status: 'pending',
    submittedTime: '2024-03-03 14:15'
  }
];

// API函数模拟
export const getAttendanceRecords = async (): Promise<AttendanceRecord[]> => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(mockAttendanceRecords), 500);
  });
};

export const getAttendanceRecordsByCourseId = async (courseId: string): Promise<AttendanceRecord[]> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockAttendanceRecords.filter(record => record.courseId === courseId));
    }, 300);
  });
};

export const saveAttendanceRecord = async (record: AttendanceRecord): Promise<AttendanceRecord> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const existingIndex = mockAttendanceRecords.findIndex(r => r.id === record.id);
      if (existingIndex >= 0) {
        mockAttendanceRecords[existingIndex] = record;
      } else {
        mockAttendanceRecords.push(record);
      }
      resolve(record);
    }, 400);
  });
};

export const getLeaveRequests = async (): Promise<LeaveRequest[]> => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(mockLeaveRequests), 500);
  });
};

export const submitLeaveRequest = async (request: LeaveRequest): Promise<LeaveRequest> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      mockLeaveRequests.push(request);
      resolve(request);
    }, 400);
  });
};

export const processLeaveRequest = async (requestId: string, status: 'approved' | 'rejected', approvedBy: string): Promise<LeaveRequest | null> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const request = mockLeaveRequests.find(r => r.id === requestId);
      if (request) {
        request.status = status;
        request.approvedBy = approvedBy;
        request.approvedTime = new Date().toISOString();
        resolve(request);
      } else {
        resolve(null);
      }
    }, 300);
  });
};

export const getAttendanceStatistics = async (courseId?: string): Promise<AttendanceStatistics[]> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const stats: AttendanceStatistics[] = [];
      const courseGroups = new Map<string, {name: string, records: AttendanceRecord[]}>();
      
      // 按课程分组
      mockAttendanceRecords.forEach(record => {
        if (courseId && record.courseId !== courseId) return;
        
        if (!courseGroups.has(record.courseId)) {
          courseGroups.set(record.courseId, {
            name: record.courseName,
            records: []
          });
        }
        courseGroups.get(record.courseId)?.records.push(record);
      });
      
      // 计算统计数据
      courseGroups.forEach((group, id) => {
        const totalStudents = new Set(group.records.map(r => r.studentId)).size;
        const presentCount = group.records.filter(r => r.status === 'present').length;
        const absentCount = group.records.filter(r => r.status === 'absent').length;
        const leaveCount = group.records.filter(r => r.status === 'leave').length;
        const lateCount = group.records.filter(r => r.status === 'late').length;
        const attendanceRate = totalStudents > 0 ? ((presentCount + lateCount + leaveCount) / totalStudents) * 100 : 0;
        
        stats.push({
          courseId: id,
          courseName: group.name,
          totalStudents,
          presentCount,
          absentCount,
          leaveCount,
          lateCount,
          attendanceRate: Math.round(attendanceRate * 100) / 100
        });
      });
      
      resolve(stats);
    }, 600);
  });
};

// 批准请假请求
export const approveLeaveRequest = async (requestId: string, approvedBy: string): Promise<LeaveRequest | null> => {
  return processLeaveRequest(requestId, 'approved', approvedBy);
};

// 拒绝请假请求
export const rejectLeaveRequest = async (requestId: string, approvedBy: string): Promise<LeaveRequest | null> => {
  return processLeaveRequest(requestId, 'rejected', approvedBy);
};

// 删除考勤记录
export const deleteAttendanceRecord = async (recordId: string): Promise<boolean> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const index = mockAttendanceRecords.findIndex(record => record.id === recordId);
      if (index !== -1) {
        mockAttendanceRecords.splice(index, 1);
        resolve(true);
      } else {
        resolve(false);
      }
    }, 300);
  });
};

// 更新考勤记录
export const updateAttendanceRecord = async (record: AttendanceRecord): Promise<AttendanceRecord> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const existingIndex = mockAttendanceRecords.findIndex(r => r.id === record.id);
      if (existingIndex >= 0) {
        mockAttendanceRecords[existingIndex] = {
          ...mockAttendanceRecords[existingIndex],
          ...record,
          updatedAt: new Date().toISOString()
        };
        resolve(mockAttendanceRecords[existingIndex]);
      } else {
        mockAttendanceRecords.push(record);
        resolve(record);
      }
    }, 400);
  });
};